<?php

namespace app\common\command;

use think\Exception;

class Projecttask
{

    /**
     * 项目任务提醒
     */
    public static function cron(){
        try {
            $model = new \app\admin\model\Userprojecttask();
            $smsObj = new \app\lib\Sms();

            $where = [
                'a.status' => 0,
                'a.deadline' => ['gt', time()]
            ];
            $join = [
                ['__USER__ u', 'u.id = a.executor'],
                ['__MEMBER__ m', 'm.id = u.memberId']
            ];
            $field = 'a.id, a.title, a.deadline, a.remind, m.mobile';
            // 所有项目任务
            $list = $model->alias('a')->where($where)->join($join)->field($field)->select();
            if($list){
                foreach ($list as $item) {
                    trace($item['title'] . '|' . date('Y-m-d H:i:s', $item['deadline']),'info');

                    // 任务截止时间
                    $startTime = $item['deadline'];
                    // 提醒时间
                    $endTime = $startTime - ($item['remind'] * 60*60*24);

                    // 是否需要提醒
                    if(date('Y-m-d', time()) === date('Y-m-d', $endTime)){
                        // 短信提醒
                        $mobile = $item['mobile'];
                        if ($mobile) {
                            $message = '';
                            $message .= "项目任务提醒：\n任务标题：" . $item['title'] . "\n";
                            $message .= '任务截止时间：' . date('Y-m-d H:i', $item['deadline']) . "\n";
                            $message .= '【智慧乡镇】';

                            $smsRes = $smsObj->sendMess($mobile, $message);
                            if (isset($smsRes)) {
                                if ($smsRes['msg'] == 'ok') {
                                    // TODO 提醒数 +1
                                    //$model->where('id', $item['id'])->setInc('countRemind');

                                    trace($mobile . ': 任务提醒短信发送成功','log');
                                } else {
                                    trace($mobile . ': 任务提醒短信发送失败','notice');
                                }
                            }
                        } else {
                            trace('没有手机号','notice');
                        }
                    }
                }
            }
        } catch (Exception $e) {
            trace($e->getMessage(),'error');
        }
    }

}